<template>
	<div>
		<xn-form-container
			:title="formData.id ? '编辑' : '新增'"
			width="1000"
			:visible="visible"
			:destroy-on-close="true"
			@close="onClose"
		>
			<a-form
				:wrapper-col="{ span: 16 }"
				:label-col="{ span: 8 }"
				autocomplete="off"
				labelAlign="right"
				ref="formRef"
				:model="formData"
				:rules="formRules"
			>
				<a-row>
					<a-col :span="12">
						<a-form-item label="仓库名称" name="warehouseId">
							<xn-page-selector
								@change="onWarehouseChange"
								ref="warehouseRef"
								:field-names="{ label: 'warehouseName', value: 'id' }"
								:page-function="(param) => storeCenterApi.getPage(param)"
								v-model:value="formData.warehouseId"
								placeholder="请选择仓库"
							>
							</xn-page-selector>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="仓库编号" name="warehouseId">
							<a-input readonly placeholder="请选择仓库" v-model:value="formData.warehouseNum" />
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="12">
						<a-form-item label="领料部门" name="deptId">
							<a-tree-select
								v-model:value="formData.deptId"
								style="width: 100%"
								:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
								placeholder="请选择领料部门"
								allow-clear
								tree-default-expand-all
								:tree-data="treeData"
								:field-names="{
									children: 'children',
									label: 'name',
									value: 'id'
								}"
								selectable="false"
								tree-line
							></a-tree-select>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="实发数量" name="issued">
							<a-input placeholder="请输入实发数量" v-model:value="formData.issued" />
						</a-form-item>
					</a-col>
				</a-row>

				<a-row>
					<a-col :span="12">
						<a-form-item label="领料日期" name="materialDate">
							<a-date-picker
								format="YYYY-MM-DD"
								placeholder="请选择领料日期"
								style="width: 100%"
								v-model:value="formData.materialDate"
							/>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="24">
						<a-row>
							<a-button type="primary" class="childAddButton" @click="addProduct()">
								<PlusOutlined />
								新增
							</a-button>
							<a-popconfirm title="是否删除?" @confirm="removeGoods()">
								<a-button style="margin-left: 12px" type="remove" danger>
									<LineOutlined />
									删除
								</a-button>
							</a-popconfirm>
						</a-row>
						<a-table
							:row-selection="options.rowSelection"
							:pagination="false"
							:columns="goodsColumns"
							:data-source="formData.produceMaterialDetailAddParamList"
							:scroll="{ x: 1000 }"
						>
							<template #bodyCell="{ index, record, column }">
								<template v-if="column.dataIndex === 'index'">
									<span>{{ index + 1 }}</span>
								</template>

								<template v-if="column.dataIndex === 'takeDeliveryNum'">
									<a-input
										@input="takeDeliveryNumChange(record)"
										:style="{ width: column.width }"
										v-model:value="record.takeDeliveryNum"
									/>
								</template>

								<template v-if="column.dataIndex === 'taxPrice'">
									<a-input
										@input="taxChange(record)"
										:style="{ width: column.width }"
										v-model:value="record.taxPrice"
									/>
								</template>

								<template v-if="column.dataIndex === 'noTaxPrice'">
									<a-input
										@input="excludingTaxChange(record)"
										:style="{ width: column.width }"
										v-model:value="record.noTaxPrice"
									/>
								</template>

								<template v-if="column.dataIndex === 'remark'">
									<a-input :style="{ width: column.width }" v-model:value="record.remark" />
								</template>
							</template>
						</a-table>
					</a-col>
				</a-row>
				<div style="margin-top: 15px">
					<span style="color: #333; font-size: 16px; font-weight: 600">合计</span>
				</div>
				<a-row :gutter="24" style="margin-bottom: 50px; margin-top: 15px; margin-left: 20px">
					<a-col :span="6">
						<div style="margin-right: 12px; display: inline-block">
							<span>出库数量:</span>
						</div>
						<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="quantity" />
					</a-col>
					<a-col :span="6">
						<div style="margin-right: 12px; display: inline-block">
							<span>含税总金额</span>
						</div>
						<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="taxAmount" />
					</a-col>
					<a-col :span="6">
						<div style="margin-right: 12px; display: inline-block">
							<span>不含税总金额</span>
						</div>
						<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="noTaxAmount" />
					</a-col>
				</a-row>
			</a-form>

			<template #footer>
				<a-button type="primary" @click="onSubmit" :loading="submitLoading">提交</a-button>
			</template>
		</xn-form-container>
		<productSelector
			:data-provider="getOrderDetailList"
			:columns="selectorColumns"
			@onProductChange="onProductChange"
			ref="productsRef"
		/>
	</div>
</template>

<script setup name="produceReceiveForm">
	import { required, rules } from '@/utils/formRules'
	import storeCenterApi from '@/api/base_data/storeCenterApi'
	import producematerialApi from '@/api/produce/producematerialApi'
	import warehouseApi from '@/api/warehouse/warehouseApi'
	import bizPositionApi from '@/api/biz/bizPositionApi'
	import xnPageSelector from '@/components/XnPageSelect/index.vue'
	import dayjs from 'dayjs'
	import { ref } from 'vue'
	import { message } from 'ant-design-vue'
	import productSelector from '@/components/Selector/productSelector.vue'
	// 定义emit事件
	//PROCUREMENT_PARTNERS
	const emit = defineEmits({ successful: null })
	// 默认是关闭状态
	const visible = ref(false)
	const productsRef = ref()
	const formRef = ref()
	const formData = ref({})
	const warehouseRef = ref()
	const submitLoading = ref(false)
	const quantity = ref(0)
	const taxAmount = ref(0)
	const noTaxAmount = ref(0)
	const options = {
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}

	const selectedRowKeys = ref([])
	// 打开抽屉
	const onOpen = (record) => {
		formData.value = {}
		visible.value = true
		if (record) {
			let params = { ...record }
			params.materialDate = ref(dayjs(params.materialDate))
			formData.value = params
			loadDetail(record.id)
		} else {
			formData.value = {
				materialDate: ref(dayjs())
			}
		}
		bizPositionApi.positionOrgTreeSelector().then((res) => {
			treeData.value = res
		})
		nextTick(() => {
			warehouseRef.value.onPage({})
		})
	}

	const formatPrice = (text) => {
		let value = text.match(/^\d*(\.?\d{0,2})/g)[0] || null
		if (isNaN(value)) {
			return ''
		}
		return value
	}
	const totalOrderNum = () => {
		let orderList = formData.value.produceMaterialDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let orderNum = it['takeDeliveryNum']
			if (orderNum) {
				amount += parseInt(orderNum)
			}
		})
		return amount
	}

	const totalExcludingTaxTax = () => {
		let orderList = formData.value.produceMaterialDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let noTaxPrice = it['noTaxPrice']
			if (noTaxPrice) {
				amount += parseFloat(noTaxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}
	const totalTax = () => {
		let orderList = formData.value.produceMaterialDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let taxPrice = it['taxPrice']
			if (taxPrice) {
				amount += parseFloat(taxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}

	const taxChange = (record) => {
		record.taxPrice = formatPrice(record.taxPrice)
		taxAmount.value = totalTax()
	}

	const excludingTaxChange = (record) => {
		record.noTaxPrice = formatPrice(record.noTaxPrice)
		noTaxAmount.value = totalExcludingTaxTax()
	}

	const takeDeliveryNumChange = (record) => {
		let value = parseInt(record.takeDeliveryNum.replace(/[^\d]+/g, ''))
		if (isNaN(value)) {
			record.takeDeliveryNum = ''
		} else {
			record.takeDeliveryNum = value
		}
		quantity.value = totalOrderNum()
	}
	const loadDetail = (id) => {
		producematerialApi
			.detail({
				id: id
			})
			.then((res) => {
				formData.value.produceMaterialDetailAddParamList = res.proProduceMaterialDetailList.map((it) => {
					it['materialName'] = it['proMaterial'].name
					it['code'] = it['proMaterial']['code']
					it['waresPrice'] = it['proMaterial'].unitPrice
					it['waresNum'] = it['proMaterial'].waresNum
					it['brand'] = it['proMaterial'].brand
					it['spec'] = it['proMaterial'].spec
					it['key'] = it['materialId']
					return it
				})
				quantity.value = totalOrderNum()
				taxAmount.value = totalTax()
				noTaxAmount.value = totalExcludingTaxTax()
			})
			.catch(() => {})
	}
	// 定义机构元素
	const treeData = ref([])

	const onWarehouseChange = (id, item) => {
		formData.value.warehouseNum = item.warehouseNum
	}

	// 关闭抽屉
	const onClose = () => {
		visible.value = false
	}
	const getOrderDetailList = (parameter) => {
		return warehouseApi
			.warehousenumPage(
				Object.assign(parameter, {
					warehouseId: formData.value.warehouseId,
					category:"物料"
				})
			)
			.then((data) => {
				data.records.forEach((it) => {
					it['key'] = it['materialId']
					it['id'] = it['materialId']
					it['remark'] = ''
				})
				return data
			})
			.catch(() => {})
	}

	// 默认要校验的
	const formRules = {
		warehouseId: [required('请选择仓库')],
		issued: [required('请输入实发数量'), rules.number],
		totalAmount: [required('请输入总金额'), rules.price],
		deptId: [required('请选择部门')],
		materialDate: [required('请选择领料日期')]
	}

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				let orderList = toRaw(formData.value.produceMaterialDetailAddParamList) || []
				if (orderList.length <= 0) {
					message.error('请添加商品')
					return
				}
				let itemRules = [
					{
						field: 'takeDeliveryNum',
						error: '退料数量不能为空!'
					}
				]
				let msg = null
				for (let i = 0; i < orderList.length; i++) {
					for (let rule of itemRules) {
						let item = orderList[i]
						let itemValue = item[rule['field']]
						if (!itemValue) {
							msg = `第${i + 1}行${rule['error']}`
							break
						}
					}
				}

				if (msg) {
					message.error(msg)
					return
				}
				let formValue = formData.value
				let formatMaterialDate = formValue.materialDate.format('YYYY-MM-DD HH:mm:ss')
				let totalAmount = parseFloat(taxAmount.value) + parseFloat(noTaxAmount.value)
				let params = {
					materialDate: formatMaterialDate,
					warehouseId: formValue.warehouseId,
					quantity: quantity.value,
					issued: formValue.issued,
					totalAmount: totalAmount,
					deptId: formValue.deptId,
					id: formValue.id
				}
				if (formValue.id) {
					params['produceMaterialDetailEditParamList'] = orderList
				} else {
					params['produceMaterialDetailAddParamList'] = orderList
				}
				producematerialApi
					.addOrEdit(params)
					.then(() => {
						visible.value = false
						emit('successful')
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})

	const removeGoods = () => {
		let datas = formData.value.produceMaterialDetailAddParamList || []
		selectedRowKeys.value.forEach((element) => {
			let index = datas.findIndex((it) => {
				console.log(element, it)
				return it['id'] == element
			})
			if (index >= 0) {
				datas.splice(index, 1)
			}
		})
		selectedRowKeys.value = []
		quantity.value = totalOrderNum()
		taxAmount.value = totalTax()
		noTaxAmount.value = totalExcludingTaxTax()
	}

	const addProduct = () => {
		if (!formData.value.warehouseId) {
			message.error('请选择仓库')
			return
		}
		productsRef.value.showDialog(formData.value.produceMaterialDetailAddParamList)
	}
	const onProductChange = (items) => {
		let produceMaterialDetailAddParamList = formData.value.produceMaterialDetailAddParamList || []
		items.forEach((it) => {
			if (!it['receiveNum']) {
				it['receiveNum'] = 0
			}
			let find = produceMaterialDetailAddParamList.find((item) => {
				return item['materialId'] == it['materialId']
			})
			if (find) {
				it = Object.assign(it, find)
			}
		})
		formData.value.produceMaterialDetailAddParamList = items
	}

	const goodsColumns = [
		{
			title: '序号',
			width: 80,
			dataIndex: 'index',
			align: 'center'
		},
		{
			title: '商品编号',
			width: 120,
			dataIndex: 'code',
			align: 'center',
			ellipsis: true
		},
		{
			title: '商品名称',
			dataIndex: 'materialName',
			width: 120,
			align: 'center',
			ellipsis: true
		},
		{
			title: '单位',
			dataIndex: 'unit',
			width: 120,
			align: 'center',
			ellipsis: true
		},
		{
			title: '规格型号',
			dataIndex: 'spec',
			width: 120,
			align: 'center',
			ellipsis: true
		},

		{
			title: '库存数量',
			dataIndex: 'waresNum',
			width: 120,
			align: 'center'
		},

		{
			title: '出库数量',
			dataIndex: 'takeDeliveryNum',
			width: 120,
			align: 'center'
		},
		{
			title: '含税金额',
			dataIndex: 'taxPrice',
			width: 120,
			align: 'center'
		},
		{
			title: '不含税金额',
			dataIndex: 'noTaxPrice',
			width: 140,
			align: 'center'
		},

		{
			title: '备注',
			dataIndex: 'remark',
			width: 200,
			align: 'center'
		}
	]

	const selectorColumns = [
		{
			title: '序号',
			dataIndex: 'index',
			ellipsis: true,
			width: 80,
			align: 'center'
		},
		{
			title: '商品编号',
			width: 100,
			dataIndex: 'code',
			align: 'center',
			ellipsis: true
		},
		{
			title: '商品名称',
			width: 120,
			dataIndex: 'materialName',
			align: 'center',
			ellipsis: true
		},
		{
			title: '品牌',
			width: 100,
			dataIndex: 'brand',
			align: 'center',
			ellipsis: true
		},
		{
			title: '规格',
			width: 100,
			dataIndex: 'spec',
			align: 'center',
			ellipsis: true
		},
		{
			title: '商品单价',
			width: 100,
			dataIndex: 'unitPrice',
			align: 'center',
			ellipsis: true
		}
	]
</script>

<style scoped :type="less">
	.childAddButton {
		margin-bottom: 10px;
	}
</style>
